package com.xdf.whiteaccount.service;

import com.xdf.whiteaccount.cloudservice.QrLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @program: white-account
 * @description: websocket服务
 * @author: 张柯
 * @create: 2021-06-11 08:58
 **/
//@ServerEndpoint("/ws/{uuid}")
//@Component
//@Slf4j
public class WebsocketServer {
    private QrLogService qrLogService;
    private static AtomicInteger count = new AtomicInteger(0);
    private static ConcurrentHashMap<String, Session> sessions = new ConcurrentHashMap<>();
    private String key;
    @Autowired
    public void setQrLogService(QrLogService qrLogService) {
        this.qrLogService = qrLogService;
    }

    /**
     * websocket开启
     */
    @OnOpen
    public void onOpen(Session session, String id) {
        sessions.put(id, session);
        this.key = id;
        count.addAndGet(1);
//        log.debug("新加入的uuid:" + id);
    }

    /**
     * 关闭
     */
    @OnClose
    public void onClose() {
        sessions.remove(key);
        count.decrementAndGet();
    }

    /**
     * 发送信息
     * @param session
     * @param message
     */
    @OnMessage
    public void sendMessage(Session session, String message) {
        if (session != null) {

        }
    }

    /**
     * 错误
     *
     * @param session
     * @param throwable
     */
    @OnError
    public void onError(Session session, Throwable throwable) {
        throwable.printStackTrace();
    }

}
